﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.Management;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Write.API.Appcation.Commands.Management;

namespace MedicalPCTerminal.Write.API.Appcation.CommandHandlers.Management
{
    /// <summary>
    /// 处理添加随访计划命令
    /// </summary>
    public class AddFollowCommandHandler : IRequestHandler<AddFollowCommand, APIResult<object>>
    {
        private readonly SqlSugarContext sqlSugar;
        private readonly IMapper mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sqlSugar">SQL Sugar上下文</param>
        /// <param name="mapper">映射器</param>
        public AddFollowCommandHandler(SqlSugarContext sqlSugar, IMapper mapper)
        {
            this.mapper = mapper;
            this.sqlSugar = sqlSugar;
        }
        
        /// <summary>
        /// 处理方法
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public Task<APIResult<object>> Handle(AddFollowCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            try
            {
                var entity = mapper.Map<Follow>(request);
                var i= sqlSugar.db.Insertable(entity).ExecuteCommand();
                if (i > 0)
                {
                    var form=sqlSugar.db.Queryable<Basic>().Where(x => x.BasicId == request.BasicId).First();
                    form.Status = "已随访";
                    var j = sqlSugar.db.Updateable(form).ExecuteCommand();
                    result.Code = APIEnum.添加成功;
                    result.Msg = APIEnum.添加成功.ToString();
                    result.data = entity;
                }
                else
                {
                    result.Code = APIEnum.添加失败;
                    result.Msg = APIEnum.添加失败.ToString();
                }
                return Task.FromResult(result);
            }
            catch (Exception)
            {
                result.Code = APIEnum.添加失败;
                result.Msg = "处理随访添加请求时发生异常";
                return Task.FromResult(result);
            }
        }
    }
}
